<?php
/** @noinspection PhpMissingReturnTypeInspection */
declare (strict_types=1);

namespace app\course\logic\video\admin;

use app\admin\logic\system\Log;
use app\common\exception\LogicException;
use app\common\library\Queue;
use app\course\event\subscribes\course\ExamineNotify;
use app\course\model\video\admin\ExamineVideoSection as ExamineVideoSectionModel;
use app\school\logic\school\School;
use think\db\exception\DbException;
use think\facade\Event;

/**
 * 后台管理逻辑层
 */
class ExamineVideoSection extends ExamineVideoSectionModel
{

    /**
     * 获取待审核课时
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-09
     *
     * @param array $map
     * @return mixed [type]                         [description]
     * @throws DbException
     */
    public function getList(array $map = [])
    {
        $builder = $this->getBuilder();
        $list    = $builder->where($map)->order('__TABLE__.create_time', 'DESC')->hidden(['video'])->paginate($this->getListRows());

        return app(Video::class)->parseList($list);

    }

    /**
     * 审核
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-16
     *
     * @param int   $id   [description]
     * @param array $data [description]
     */
    public function doExamine(int $id, array $data)
    {
        $builder      = $this->getBuilder();
        $videoSection = $builder->where('__TABLE__.id', $id)->findOrFail();
        $pass         = $data['status'] === 1 ? 1 : 0;
        $title        = $videoSection->course_title . "-" . $videoSection->title;

        // 是否通过
        if ($pass === 1) {
            $mhm_id = request()->user->getAttr('mhm_id');
            // 如果为机构审核操作, 则检测是否要进入平台审核流程
            if ($mhm_id != 1) {
                $school = app(School::class)->where('id', $mhm_id)->findOrFail();
                // 是否需要平台再审核 is_audit为1表示需要平台再审,此时状态改为3
                $status = $school->getAttr('is_audit') == 1 ? 3 : 1;
            } else {
                // 为平台审核操作直接通过
                $status = 1;
            }
            // $msg = "课时《" . $title . "》已通过审核";
        } else {
            // 未通过审核
            $status = 0;
            // $msg    = "课时《" . $title . "》未通过审核，驳回理由：" . $data['reason'];
        }

        $videoSection->status = $status;
        if (!$videoSection->save()) {
            throw new LogicException('操作失败');
        }

        // 审核通过，发送消息给购买用户，提示课时更新
        if ($status === 1) {
            // 队列处理课程、课时提醒
            Queue::push('CourseNotify', [
                'type'   => 2,
                'source' => $videoSection->course_id,
            ], 30);
            Log::write('点播课时审核通过【' . $title . '】', 'video', 'update', true);
        } else {
            Log::write('点播课时审核驳回【' . $title . '】', 'video', 'update', true);
        }

        // 课时审核消息通知
        Event::subscribe(ExamineNotify::class);
        Event::trigger('ExamineNotify', [
            'type' => 'examine',   // 后台审核结果通知，submit为前端讲师提交
            'data' => [
                'sec_update_teacher' => $videoSection->teacher_id,
                'sec_update_admin'   => $videoSection->update_admin,
                'sec_title'          => $title,
                'status'             => $status,
                'reason'             => $data['reason'] ?? '',
                'admin_mhm_id'       => request()->user->getAttr('mhm_id'),
            ]
        ]);
    }

    /**
     * 构造基础条件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-16
     *
     */
    protected function getBuilder()
    {
        $withJoin = [
            'video' => [
                'video.title'      => 'course_title',
                'video.mhm_id'     => 'mhm_id',
                'video.teacher_id' => 'teacher_id',
            ],
        ];
        $mhm_id   = request()->user->getAttr('mhm_id');
        // 是否平台
        if ($mhm_id == 1) {
            $builder = $this->withJoin($withJoin)->where(function ($query) {
                // 当前机构需要审核的
                $where1 = [['__TABLE__.status', '=', 2], ['video.mhm_id', '=', 1]];
                // 当前待平台审核的
                $where2 = [['__TABLE__.status', '=', 3]];
                $query->whereOr([$where1, $where2]);
            })->where('video.status', 1);
        } else {
            $builder = $this->where('__TABLE__.status', 2)->withJoin($withJoin)->where('video.mhm_id', $mhm_id);
        }

        return $builder;
    }
}
